/*
 * @Author: 王雁鹏
 * @Date: 2023-04-27 07:25:22
 * @LastEditTime: 2023-08-01 10:34:31
 * @LastEditors: Please set LastEditors
 * @Description: 
 * @FilePath: \expressf:\web-vue\bs-nodejs-background-code\utils\router.js
 * -------------------------------------
 */
const multer = require("multer")
const path = require("path")
var express = require('express');
let dbMap = require('./fieldMap.js');
let { filterBool } = require("./func.js")
var router = express.Router();
class RouterController {
    constructor(params = {}) {
        this.require = []
        let keys = Object.keys(params)
        if (keys.length > 0) {
            for (let i in params) {
                this.require.push({
                    key: i,
                    error: `${i}为必填项`,
                    hint: params[i]
                })
            }
        }
    }
}
// get请求检查
class GetRouter extends RouterController {
    constructor(params = {}) {
        super(params)
    }
    send(path, fn) {
        router.get(path, (req, res, next) => {
            let openid = req.headers.openid ? req.headers.openid : req.query.openid
            let { bool, code } = filterBool(path, req.query)
            if (bool == false) {
                res.send(code)
                return
            }
            if (this.require.length === 0) {
                return fn(res, { ...req.query, openid })
            }
            let examine = this.require.reduce((current, item) => {
                if (req.query[item.key]) {
                    current.success[item.key] = req.query[item.key]
                } else {
                    current.error.push(item)
                }
                return current
            }, { error: [], success: { ...req.query, openid } })
            if (examine.error.length > 0) {
                res.send({ warn: examine.error })
            } else {
                fn(res, examine.success)
            }
        })
    }
}

// post请求检查
class PostRouter extends RouterController {
    constructor(params = {}) {
        super(params)
    }
    send(path, fn) {
        router.post(path, (req, res, next) => {
            let openid = req.headers.openid ? req.headers.openid : req.body.openid
            let examine = this.require.reduce((current, item) => {
                if (req.body[item.key]) {
                    current.success[item.key] = req.body[item.key]
                } else {
                    current.error.push(item)
                }
                return current
            }, { error: [], success: { ...req.body, openid } })
            if (examine.error.length > 0) {
                res.send({ warn: examine.error })
            } else {
                fn(res, examine.success)
            }
        })
    }
}

class Upload extends RouterController {
    constructor(params = {}) {
        super(params)
        // this.http = "http://162.14.64.133:8721/tieQuan/"
        this.http = "http://162.14.80.40:8721/"
        this.load = this.multer()
        // this.url = params.url || "../../downloads/tieQuan"
        this.url = params.url || "../../downloads/tieQuan"
        this.name = params.name || "file"
        this.format = this.filter(params.type)
    }
    filter(arr = ["*"]) {
        let typeFilter = {
            image: ['image/jpeg', 'image/png'],
        }
        return (val) => {
            return arr.map(item => {
                if (typeFilter[item]) {
                    return typeFilter[item].indexOf(val) > -1
                }
                return true
            }).filter(item => item).length > 0
        }
    }
    multer() {
        var storage = multer.diskStorage({
            // 配置文件上传后存储的路径
            destination: (req, file, cb) => {
                if (this.format(file.mimetype)) {
                    // NodeJS的两个全局变量
                    cb(null, "C:/serve/image")
                } else {
                    // 3.1.2 限制其他文件上传类型
                    cb({ error: 'Mime type not supported' })
                }

            },
            // 配置文件上传后存储的路径和文件名
            filename: function (req, file, cb) {
                cb(null, Date.now() + path.extname(file.originalname))
            }
        })
        return multer({ storage: storage })
    }
    sendField(path, fn) {
        const cpUpload = this.load.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
        router.post(path, cpUpload, (req, res, next) => {
            if (fn) {
                fn(res, req.body)
            }
        });
    }
    sendList(path, fn) {
        router.post(path, this.load.array('files', 10), (req, res, next) => {
            if (fn) {
                fn(res, req.body)
            }
        });
    }
    send(path, fn) {
        router.post(path, this.load.single(this.name), (req, res, next) => {
            let examine = this.require.reduce((current, item) => {
                if (req.body[item.key]) {
                    current.success[item.key] = req.query[item.key]
                } else {
                    current.error.push(item)
                }
                return current
            }, { error: [], success: {} })
            if (examine.error.length > 0) {
                res.send({ warn: examine.error })
            } else {
                fn(res, { path: `${this.http}${req.file.filename}` })
            }
        })
    }
}

const DBMap = (name, obj) => {
    let res = {}
    if (dbMap[name]) {
        for (let i in dbMap[name]) {
            if (obj[i] !== null && obj[i] !== undefined) {
                res[dbMap[name][i]] = obj[i]
            }
        }
    }
    return res
}

const MapDB = (name, obj) => {
    let res = {}
    if (dbMap[name]) {
        for (let i in dbMap[name]) {
            let key = dbMap[name][i]
            if (obj[key] !== null && obj[key] !== undefined) {
                if (/\[(.+?)\]/.test(obj[key])) {
                    res[i] = JSON.parse(obj[key])
                } else {
                    res[i] = obj[key]
                }
            }
        }
    }
    return res
}

module.exports = {
    MapDB,
    DBMap,
    Upload,
    router,
    GetRouter,
    PostRouter
}